/**
 * 
 */
package com.cqan.account.rest.impl;

import static com.cqan.common.Constant.getHeader;
import static com.cqan.util.http.HttpStatus.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.ws.rs.core.HttpHeaders;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.cqan.account.entity.User;
import com.cqan.account.entity.resp.ResultResp;
import com.cqan.account.entity.resp.UserResp;
import com.cqan.account.rest.AccountRestService;
import com.cqan.account.service.UserService;
import com.cqan.log.entity.GenericLog;
import com.cqan.log.service.GenericLogService;
import com.cqan.orm.PropertyFilter.MatchType;
import com.cqan.service.rest.BaseRestService;
import com.cqan.system.service.SystemConfigService;
import com.cqan.util.encode.EncodeUtils;
import com.cqan.util.pool.ObjectCachePool;

/**
 * @Description 用户REST服务层
 * @author slaton.wu@gmail.com
 * @date 2012-7-4下午6:16:20
 *
 */

@Component("accountRestService")
public class AccountRestServiceImpl extends BaseRestService implements AccountRestService {
	
	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="objectCachePool")
	private ObjectCachePool<String> pool;
	
	@Resource(name="systemConfigService")
	private SystemConfigService systemConfigService;
	
	@Resource(name="genericLogService")
	private GenericLogService genericLogService;
	
	@Override
	public ResultResp login(String username,String password,HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		UserResp userResp = new UserResp();
		password = EncodeUtils.md5(password, username);
		try {
			User user = userService.getUserByUserName(username);
			if (user==null) {
				resp.setCode(NO_CONTENT);
			}else if (password==null||!user.getPassword().equals(password)) {
				resp.setCode(BAD_REQUEST);
			}else if(!user.isEnabled()){
				resp.setCode(UNAUTHORIZED);
			}else{
				genericLogService.add(new GenericLog(headers, req.getRemoteAddr(),"login"));
				user.setLastLoginTime(new Date());
				user.setLastLoginIp(req.getRemoteAddr());
				userService.update(user);
				userResp.setUserResp(user);
				userResp.setUserToken(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode(INTERNAL_SERVER_ERROR);
			logger.error("login error message={}",e.getMessage());
		}
		resp.setUserResp(userResp);
		return resp;
	}

	
	@Override
	public ResultResp register(String username,String password,HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		UserResp userResp = new UserResp();
		try {
			Map<String,String> header = getHeader(headers);
			String did = header.get("did");
			User user = userService.getUserByUserName(username);
			if (user!=null) {
				userResp.setUsername(username);
				resp.setUserResp(userResp);
				resp.setCode(ACCEPTED);
			}else{
				user = new User();
				List<User> users = userService.findBy("did", did, MatchType.EQ);
				if(users!=null&&(users.size()==1&&users.get(0).getUserGrade()==0)){
					user = users.get(0);
				}
				user.setDid(did);
				user.setUserGrade(1);
				user.setCreateTime(Calendar.getInstance().getTime());
				user.setEmail(username);
				user.setRegIp(req.getRemoteAddr());
				user.setLastLoginIp(user.getRegIp());
				user.setLastLoginTime(Calendar.getInstance().getTime());
				user.setPassword(EncodeUtils.md5(username, password));
				user.setUsername(username);
				user.setEnabled(true);
				user.setBirthday(Calendar.getInstance().getTime());
				userService.add(user);
				userResp.setUserResp(user);
				userResp.setUserToken(user);
				genericLogService.add(new GenericLog(headers, req.getRemoteAddr(),"register"));
			}
			resp.setUserResp(userResp);
		} catch (Exception e) {
			resp.setCode(INTERNAL_SERVER_ERROR);
			e.printStackTrace();
		}
		
		return resp;
	}


	@Override
	public ResultResp getUserInfo(Long id,HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		try {
			UserResp userResp = new UserResp();
			User user =userService.get(id);
			if (user!=null&&user.getUsername()!=null) {
				resp.setCode(OK);
				userResp.setUserResp(user);
				resp.setUserResp(userResp);
				genericLogService.add(new GenericLog(headers, req.getRemoteAddr(),"getUserInfo"));
			}else{
				resp.setCode(NO_CONTENT);
			}
		} catch (Exception e) {
			resp.setCode(INTERNAL_SERVER_ERROR);
			e.printStackTrace();
		}
		return resp;
	}


	
	@Override
	public ResultResp findPwd(String username,HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		try {
			User user = userService.findBy("username", username);
			if (user==null) {
				resp.setCode(BAD_REQUEST);
			}else{
				systemConfigService.sendNoticeEmail(user.getEmail(),user.getUsername());
				genericLogService.add(new GenericLog(headers, req.getRemoteAddr(),"findPwd"));
				resp.setCode(OK);
			}
		} catch (Exception e) {
			resp.setCode(INTERNAL_SERVER_ERROR);
			e.printStackTrace();
		}
		return resp;
	}

	@Override
	public ResultResp userModify(String nickname, String phone,String realName,String address,
			String email,String birthday, String degree, String sex,
			String avatar,  HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		UserResp userResp = new UserResp();
		 try {
			Map<String, String> header = getHeader(headers);
			 if (header==null||header.get("uid")==null) {
				 resp.setCode(BAD_REQUEST);
				 return resp;
			}
			 String uid = header.get("uid");
			 User user = userService.get(Long.parseLong(uid));
			 if (user==null) {
				 resp.setCode(BAD_REQUEST);
				 return resp;
			}else if(user.getUserGrade()==0){
				 resp.setCode(UNAUTHORIZED);
				return resp;
			}
			 if (!StringUtils.isBlank(encodeing(nickname))) {
				 user.setNickname(nickname);
			}
			 if (!StringUtils.isBlank(encodeing(degree))) {
				 user.setDegree(degree);
			 }
			 if (!StringUtils.isBlank(encodeing(sex))) {
				 user.setSex(sex);
			 }
			 if (!StringUtils.isBlank(avatar)) {
				 user.setAvatar(avatar);
			 }
			 if (!StringUtils.isBlank(phone)) {
				 user.setPhone(phone);
			 }
			 if (!StringUtils.isBlank(encodeing(realName))) {
				 user.setRealName(realName);
			 }
			 if (!StringUtils.isBlank(encodeing(address))) {
				 user.setAddress(address);
			 }
			 userService.update(user);
			 userResp.setUserResp(user);
			 resp.setUserResp(userResp);
			 resp.setCode(OK);
			 genericLogService.add(new GenericLog(headers, req.getRemoteAddr(),"userModify"));
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode(INTERNAL_SERVER_ERROR);
		}
		return resp;
	}


	@Override
	public ResultResp resetPwd(String username, String password, String verifycode, HttpHeaders headers) {
		ResultResp resp = new ResultResp();
		UserResp userResp = new UserResp();
		try {
			String code = pool.get(username);
			if (username==null||password==null||verifycode==null||code==null||!code.equals(verifycode)) {
				resp.setCode(BAD_REQUEST);
				return resp;
			}
			User user = userService.getUserByUserName(username);
			user.setPassword(EncodeUtils.md5(password, username));
			userService.update(user);
			user.setLastLoginTime(new Date());
			user.setLastLoginIp(req.getRemoteAddr());
			userService.update(user);
			userResp.setUserResp(user);
			userResp.setUserToken(user);
			resp.setCode(OK);
			genericLogService.add(new GenericLog(headers, req.getRemoteAddr(),"resetPwd"));
		} catch (Exception e) {
			resp.setCode(INTERNAL_SERVER_ERROR);
			e.printStackTrace();
		}
		return resp;
	}

	

}
